package com.fy.module.qu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.common.dto.PageDto;
import com.fy.common.dto.PageResult;
import com.fy.module.qu.common.dto.QuPage;
import com.fy.module.qu.common.dto.QuSave;
import com.fy.module.qu.common.enums.ApiErrorEnum;
import com.fy.module.qu.common.exception.ServiceException;
import com.fy.module.qu.common.vo.ApiRest;
import com.fy.module.qu.entity.Qu;
import com.fy.module.qu.entity.QuAnswer;
import com.fy.module.qu.entity.QuRepo;
import com.fy.module.qu.mapper.QuAnswerMapper;
import com.fy.module.qu.mapper.QuMapper;
import com.fy.module.qu.mapper.QuPageMapper;
import com.fy.module.qu.mapper.QuRepoMapper;
import com.fy.module.qu.service.IQuAnswerService;
import com.fy.module.qu.service.IQuRepoService;
import com.fy.module.qu.service.IQuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.bean.BeanUtil;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 问题题目 服务实现类
 * </p>
 *
 * @author
 * @since 2023-03-21
 */
@Service
@Slf4j
public class QuServiceImpl extends ServiceImpl<QuMapper, Qu> implements IQuService {

    @Autowired
    private QuAnswerMapper quAnswerMapper;

    @Autowired
    private QuRepoMapper quRepoMapper;

    @Autowired
    private IQuAnswerService answerService;

    @Autowired
    private IQuRepoService repoService;

    @Autowired
    private QuMapper quMapper;


    @Autowired
    private QuPageMapper quPageMapper;

    /**
     * 新增题目
     * @param quSave
     * @return
     */
    @Transactional
    @Override
    public ApiRest insertQu(QuSave quSave) {
        //参数校验
        checkSave(quSave);
        //向qu添加数据
        Qu qu = new Qu();
        BeanUtil.copyProperties(quSave,qu,true);
        qu.setId(IdWorker.getIdStr());
        qu.setCreateTime(new Date());
        qu.setUpdateTime(qu.getCreateTime());
        this.baseMapper.insert(qu);
        //向qu_answer添加数据
        List<QuAnswer> answers = quSave.getAnswers();
        for (QuAnswer answer : answers) {
            answer.setId(IdWorker.getIdStr());
            answer.setQuId(qu.getId());
            quAnswerMapper.insert(answer);
        }
        //向qu_repo中添加数据
        String[] repoIds = quSave.getRepoIds();
        for (String repoId : repoIds) {
            QuRepo quRepo = new QuRepo();
            quRepo.setId(IdWorker.getIdStr());
            quRepo.setQuId(qu.getId());
            quRepo.setRepoId(repoId);
            quRepo.setQuType(qu.getQuType());
            quRepoMapper.insert(quRepo);
        }
        log.info("{}时间{}添加题目成功","张三",new Date());
        return ApiRest.success();
    }

    /**
     * 修改题目
     * @param quSave
     * @return
     */
    @Transactional
    @Override
    public ApiRest updateQu(QuSave quSave) {
        //参数校验
        checkSave(quSave);
        Qu qu = this.baseMapper.selectById(quSave.getId());
        if (qu == null) {
            throw new ServiceException(ApiErrorEnum.QU_ERROR);
        }
        //修改qu
        BeanUtil.copyProperties(quSave, qu, true);
        qu.setUpdateTime(new Date());
        this.baseMapper.updateById(qu);
        //修改answer   先删除当前题目所有的answer在添加
        UpdateWrapper<QuAnswer> quAnswerUpdateWrapper = new UpdateWrapper<>();
        quAnswerUpdateWrapper.eq("qu_id",qu.getId());
        answerService.remove(quAnswerUpdateWrapper);
        //向qu_answer添加数据
        List<QuAnswer> answers = quSave.getAnswers();
        for (QuAnswer answer : answers) {
            answer.setId(IdWorker.getIdStr());
            answer.setQuId(qu.getId());
            quAnswerMapper.insert(answer);
        }
        //修改qu_repo   先删除当前题目所有的qu_repo在添加
        UpdateWrapper<QuRepo> quRepoUpdateWrapper = new UpdateWrapper<>();
        quRepoUpdateWrapper.eq("qu_id", qu.getId());
        repoService.remove(quRepoUpdateWrapper);
        //向qu_repo中添加数据
        String[] repoIds = quSave.getRepoIds();
        for (String repoId : repoIds) {
            QuRepo quRepo = new QuRepo();
            quRepo.setId(IdWorker.getIdStr());
            quRepo.setQuId(qu.getId());
            quRepo.setRepoId(repoId);
            quRepo.setQuType(qu.getQuType());
            quRepoMapper.insert(quRepo);
        }
        log.info("{}时间{}修改题目成功", "张三", new Date());
        return ApiRest.success();
    }

    @Transactional
    @Override
    public PageResult selectPageQu(PageDto pageDto) {
//        PageHelper.startPage(1,5);
//        List<QuPage> quPages = quPageMapper.selectQuPages(new PageDto(1, 3, ""));
//        PageInfo pageInfo = new PageInfo(quPages);
//        System.out.println(pageInfo);
//        PageResult<QuPage> quPagePageResult = new PageResult<QuPage>(pageInfo.getTotal(), pageInfo.getList(), pageInfo.getPages());
//        return quPagePageResult;
        //分页
        if (pageDto == null || pageDto.getNow() == 0 || pageDto.getNow() == null){
            pageDto.setNow(1);
            pageDto.setSize(5);
        }
        IPage<Qu> pageInfo = new Page(pageDto.getNow(), pageDto.getSize());
        IPage<Qu> quIPage = null;
        if (pageDto.getWhere() == null){
            QueryWrapper<Qu> quQueryWrapper = new QueryWrapper<>();
            quQueryWrapper.eq("id",pageDto.getWhere());
            quIPage = quMapper.selectPage(pageInfo, quQueryWrapper);
        }else {
            quIPage = quMapper.selectPage(pageInfo, null);
        }
        return new PageResult(quIPage.getTotal(),quIPage.getRecords(),quIPage.getPages());
    }



    /**
     * 通过id查询题目 答案 和关联的题库
     * @param id
     */
    @Override
    public QuPage selectQuery(String id) {
        if (id == null || "".equals(id)){
            throw new ServiceException("参数异常");
        }
        QuPage quPage = quPageMapper.selectQu(id);
        return quPage;
    }

    /**
     * 参数校验
     * @param quSave
     */
    private void checkSave(QuSave quSave) {
        if (quSave == null){
            throw new ServiceException("参数异常");
        }
        //内容不能为空
        if (quSave.getContent() == null || quSave.getContent().equals("")) {
            throw new ServiceException(ApiErrorEnum.QU_CONTENT_IS_NULL);
        }
        //未绑定题库
        if (CollectionUtils.isEmpty(Arrays.asList(quSave.getRepoIds()))){
            throw new ServiceException(ApiErrorEnum.QU_REPO_ATLEAST_ONE);
        }
        //客观题至少要包含一个备选答案
        if (quSave.getAnswers() == null || CollectionUtils.isEmpty(Arrays.asList(quSave.getAnswers()))){
            throw new ServiceException(ApiErrorEnum.QU_HAS_ANSWER);
        }
    }



}
